/*
 * @Author: silence
 * @Date: 2023-07-06 14:16:37
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-04-15 13:40:04
 * @Description: 电站设置-顶部（显示电价）
 */
import 'package:ems_neutral_app/common/widgets/cubitWidget/DividingLine.dart';
import 'package:ems_neutral_app/pages/Mine/Language/SilLocalizations/SilLocalizations.dart';
import 'package:ems_neutral_app/utils/color/ColorUtils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_utils_package/tools/SilTools.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

import '../Controller/PowerStationController.dart';

class PsSetStepLineChartView extends StatefulWidget {
  final void Function()? closeChartFunc;
  const PsSetStepLineChartView({this.closeChartFunc, super.key});

  @override
  State<PsSetStepLineChartView> createState() => _PsSetStepLineChartViewState();
}

class _PsSetStepLineChartViewState extends State<PsSetStepLineChartView> {
  List<_SalesData> data = [];

  Map _latestElectricityPriceMap = {};

  TooltipBehavior _tooltipBehavior = TooltipBehavior(enable: true);
  PowerStationController _powerStationController =
      Get.put(PowerStationController());

  /// 能否能够显示最新电价折线图
  bool _isAbleShowPrice = false;

  @override
  void initState() {
    super.initState();

    loadData();
    _powerStationController.latestElectricityPriceMap.listen((p0) {
      loadData();
      if (this.mounted) setState(() {});
    });

    _powerStationController.powerStationSetInfo.listen((p0) {
      loadData();
      if (this.mounted) setState(() {});
    });
  }

  loadData() {
    data = [];
    // 最新电价
    _latestElectricityPriceMap =
        _powerStationController.latestElectricityPriceMap;
    List categories = _latestElectricityPriceMap['categories'];
    List series = _latestElectricityPriceMap['series'];
    for (var i = 0; i < series.length; i++) {
      data.add(_SalesData(categories[i], double.parse(series[i])));
    }

    /// 处理是否显示折线图
    handleShowChartView();
  }

  /// 处理是否显示折线图
  handleShowChartView() {
    /// 当前是否是有电价数据
    List series = _latestElectricityPriceMap['series'];
    _isAbleShowPrice = (!SilTools.listIsEmpty(series)) ? true : false;

    if (_isAbleShowPrice) {
      /// 当前是否是削峰填谷模式
      int workingModeIndex =
          _powerStationController.powerStationSetInfo['eybond_ctrl_112'];
      _isAbleShowPrice = (workingModeIndex == 1);
    }

    if (this.mounted) setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return _isAbleShowPrice ? contentView() : Container();
  }

  contentView() {
    return Column(
      children: [
        Container(
          height: MediaQuery.of(context).padding.top + 40.w,
          color: ColorUtils.color_bottom_sheet,
        ),
        titleView(),
        Container(
            color: ColorUtils.color_bg,
            alignment: Alignment.center,
            child: stepLineChartView()),
        DividingLine()
      ],
    );
  }

  titleView() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      height: 40.w,
      color: ColorUtils.color_bottom_sheet,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Container(height: 24.w, width: 24.w),
          Expanded(
              child: SilText(
            LangOf(context)?.power_setting?.daily_electricity_price,
            color: ColorUtils.color_font_main,
            fontSize: 16.w,
            textAlign: TextAlign.center,
            margin: EdgeInsets.symmetric(horizontal: 5.w),
          )),
          SilButton(
            imgPath: 'imgs/common/cancel_white.png',
            imgHeight: 24.w,
            imgWidth: 24.w,
            onTapFunc: widget.closeChartFunc,
          )
        ],
      ),
    );
  }

  stepLineChartView() {
    String priceStr =
        LangOf(context)?.power_setting?.electricity ?? 'Electricity price';
    return Container(
        width: 400,
        height: 300,
        color: ColorUtils.color_bottom_sheet,
        child: SfCartesianChart(
            backgroundColor: Colors.black,
            primaryXAxis: CategoryAxis(
              borderWidth: 0,
              borderColor: Colors.transparent,
              maximum: 24,
              minimum: 0,
              interval: 2,

              /// 不显示主轴上的网格线
              majorGridLines: MajorGridLines(
                  width: 0.5, color: ColorUtils.color_subtitle), // 网格线
              majorTickLines: MajorTickLines(width: 0), // 标记线
              axisLine:
                  AxisLine(width: 1, color: ColorUtils.color_font_main), // 轴线
            ),
            primaryYAxis: NumericAxis(
              interval: 25,

              /// 不显示主轴上的网格线
              majorGridLines: MajorGridLines(
                  width: 0.5, color: ColorUtils.color_subtitle), // 网格线
              majorTickLines: MajorTickLines(width: 0), // 标记线
              axisLine:
                  AxisLine(width: 1, color: ColorUtils.color_font_main), // 轴线
            ),
            // Enable tooltip 打开工具提示
            tooltipBehavior: _tooltipBehavior,
            // 标题
            title: ChartTitle(
                text: '（EUR/MWh）',
                alignment: ChartAlignment.near,
                textStyle: TextStyle(fontSize: 14.sp, shadows: List.empty())),
            // 跟踪十字架
            crosshairBehavior: CrosshairBehavior(
              enable: true,
              activationMode: ActivationMode.singleTap,
              shouldAlwaysShow: false,
              lineType: CrosshairLineType.vertical,
              lineColor: Colors.white,
            ),

            /// 底部标志
            legend: Legend(isVisible: true),
            // 跟踪球
            trackballBehavior: TrackballBehavior(
              lineType: TrackballLineType.vertical,
              activationMode: ActivationMode.singleTap,
              enable: false,
              tooltipAlignment: ChartAlignment.near,
              shouldAlwaysShow: false,
              tooltipDisplayMode: TrackballDisplayMode.groupAllPoints,
            ),
            series: <StepLineSeries<_SalesData, String>>[
              StepLineSeries(
                  dataSource: data,
                  xValueMapper: (_SalesData sales, _) => sales.year,
                  yValueMapper: (_SalesData sales, _) => sales.sales,
                  // 不显示标志
                  isVisibleInLegend: false,
                  color: ColorUtils.color_chart_line,
                  width: 2,
                  animationDuration: 0,
                  name: priceStr
                  // width: 3
                  ),
            ]));
  }
}

class _SalesData {
  _SalesData(this.year, this.sales);

  final String year;
  final double sales;
}
